package v1

import (
	"ginblog/model"
	errMsg "ginblog/model/err"
	"ginblog/model/response"
	"ginblog/service"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"strconv"
)

// 添加用户
func UserExist(c *gin.Context) {

}

// @Summary 用户编辑
// @Description 编辑用户
// @Tags 用户
// @Accept application/json
// @Produce application/json
// @Security ApiKeyAuth
// @Success 200 {object} response.Res
// @Router /api/v1//user [put]
func Edit(c *gin.Context) {
	var (
		code errMsg.Code
		u    model.User
		p    map[string]interface{}
	)
	id, _ := strconv.Atoi(c.Param("id"))
	_ = c.ShouldBindJSON(&p)
	u.ID = uint(id)
	if code = u.Check(model.UserNeedCheck, p); code != errMsg.SUCCESS {
		response.Fail(c, code, nil)
		return
	}
	if code = u.EditUser(id, p); code != errMsg.SUCCESS {
		response.Fail(c, code, u)
		return
	}
	response.Ok(c, u)
}

// @Summary 用户列表
// @Description 用户列表
// @Tags 用户
// @Accept application/json
// @Produce application/json
// @Param pageSize query int false "pageSize 页大小"
// @Param pageNum query int false "查询参数"
// @Security ApiKeyAuth
// @Success 200 {object} response.Res
// @Router /api/v1/user [get]
func GetUsers(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))
	pageNum, _ := strconv.Atoi(c.DefaultQuery("pageNum", "1"))
	// todo 参数校验
	// 业务分层
	info, code := service.GetUser(nil, pageSize, pageNum)
	//data, err := model.GetUsers(pageSize, pageNum)
	// 错误处理
	if code != errMsg.SUCCESS {
		response.Fail(c, errMsg.DB_ERROR, nil)
		return
	}
	response.Ok(c, info)
}

// @Summary 用户添加
// @Description 添加用户
// @Tags 用户
// @Accept application/json
// @Produce application/json
// @Security ApiKeyAuth
// @Success 200 {object} response.Res
// @Router /api/v1//user [post]
func AddUser(c *gin.Context) {
	var (
		code errMsg.Code
		u    model.User
	)
	_ = c.ShouldBindJSON(&u)
	// todo 参数校验
	//if code = u.CheckUser(u.Username); code != model.SUCCESS {
	if code = u.Check([]string{"username"}); code != errMsg.SUCCESS {
		response.Fail(c, code, nil)
		return
	}
	if code = u.Create(); code != errMsg.SUCCESS {
		response.Fail(c, errMsg.ERROR, nil)
		return
	}
	response.Ok(c, u)
}

// @Summary 用户删除
// @Description 删除用户
// @Tags 用户
// @Accept application/json
// @Produce application/json
// @Security ApiKeyAuth
// @Success 200 {object} response.Res
// @Router /api/v1//user/:id [delete]
func DeleteUser(c *gin.Context) {
	id, _ := strconv.Atoi(c.DefaultQuery("id", "0"))
	u := model.User{
		Model: gorm.Model{ID: uint(id)},
	}
	code := u.Delete()
	if code != errMsg.SUCCESS {
		response.Fail(c, code, nil)
		return
	}
	response.Ok(c, nil)
}
